package cn.minimelon.api.config;

import cn.minimelon.api.constant.UserConstants;
import cn.minimelon.api.domain.common.LoginUser;
import cn.minimelon.api.service.common.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.util.PathAnalyzer;

/**
 * 登录过滤器
 *
 * @author hiro
 */
@Slf4j
@Component(index = 1)
public class TokenLoginFilter implements Filter {
    @Inject
    TokenService tokenService;

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        long start = System.currentTimeMillis();
        if (!isPublicURI(ctx.uri().getPath())) {
            LoginUser loginUser = tokenService.getLoginUser(ctx);
            if (loginUser != null) {
                ctx.attrSet(UserConstants.SYS_USER, loginUser);
            }
        }
        chain.doFilter(ctx);
        log.info("url:{} time(ms):{}", ctx.uri().getPath(), (System.currentTimeMillis() - start));
    }

    private boolean isPublicURI(String path) {
        String[] pattenArr = { "/login", "/public/**" };
        for (String patten : pattenArr) {
            if (PathAnalyzer.get(patten).matches(path)) {
                return true;
            }
        }
        return false;
    }
}
